package com.ruoyi.common.flowable;

import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.mapper.SysDeptMapper;
import com.ruoyi.common.core.mapper.SysUserMapper;
import com.ruoyi.common.utils.spring.SpringUtils;
import lombok.Data;
import org.apache.commons.collections4.CollectionUtils;
import org.flowable.bpmn.model.ExtensionAttribute;
import org.flowable.bpmn.model.UserTask;
import org.flowable.engine.RuntimeService;
import org.flowable.task.api.Task;
import org.springframework.stereotype.Component;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 获取任务候选人
 */
@Component
public class TaskCandidateUserForStaticAnalysis {
    public static SysDeptMapper getSysDeptMapper() {
        return SpringUtils.getBean(SysDeptMapper.class);
    }

    public static SysUserMapper getSysUserMapper() {
        return SpringUtils.getBean(SysUserMapper.class);
    }

    public static RuntimeService getRuntimeService() {
        return SpringUtils.getBean(RuntimeService.class);
    }

    @Data
    public static abstract class CandidateUserHandle{
        protected UserTask userTask;
        protected String lastAuditUserId;
        protected Task task;
        protected  Map vars = new HashMap();
        public List<String> getUsers(){
            if(!checkVarsIsNull()){
                return new ArrayList<>();
            }
            return this.getUserList();
        }
        protected List<String> getUserList(){
            return new ArrayList<>();
        }
        protected boolean checkVarsIsNull(){
            List<String> keys = getCheckVarsKey();
            if(CollectionUtils.isEmpty(keys)){
                keys = new ArrayList<>();
            }
            for (int i = 0; i < keys.size(); i++) {
                List<ExtensionAttribute> values = userTask.getAttributes().get(keys.get(i));
                if(CollectionUtils.isEmpty(values)){
                    return false;
                }
                if(StrUtil.isEmpty(values.get(0).getValue())){
                    return false;
                }
            }
            return true;
        }
        protected String getTaskAttributes(String key){
            List<ExtensionAttribute> values = userTask.getAttributes().get(key);
            if(CollectionUtils.isEmpty(values)){
                return "";
            }
            return values.get(0).getValue();
        }
        protected abstract List<String> getCheckVarsKey();
    }

    /**根据人员id获取用户*/
    public static class CustomCandidateUsers extends CandidateUserHandle{
        protected List<String> getUserList(){
            return Arrays.asList(getTaskAttributes("customCandidateUsers").split(","));
        }

        @Override
        protected List<String> getCheckVarsKey() {
            return List.of("customCandidateUsers");
        }
    }

    /**根据部门获取用户*/
    public static class CustomCandidateDepts extends CandidateUserHandle{
        protected List<String> getUserList(){
            String depts = getTaskAttributes("customCandidateDepts");
            String posts = getTaskAttributes("customCandidatePosts");
            List<String> postNameList = Arrays.asList(posts.split(",")).stream().filter(r->StrUtil.isNotBlank(r)).collect(Collectors.toList());
            List<SysUser> userList = getSysDeptMapper().selectUserByDeptIds(Arrays.asList(depts.split(",")),postNameList);
            return userList.stream().map(r->r.getUserId()+"").collect(Collectors.toList());
        }

        @Override
        protected List<String> getCheckVarsKey() {
            return List.of("customCandidateDepts");
        }
    }
    /**根据岗位获取用户*/
    public static class CustomCandidatePosts extends CandidateUserHandle{
        protected List<String> getUserList(){
            String customCandidatePosts = userTask.getAttributes().get("customCandidatePosts").get(0).getValue();
            List<SysUser> userList = getSysUserMapper().selectUserByPostIds(Arrays.asList(customCandidatePosts.split(",")));
            return userList.stream().map(r->r.getUserId()+"").collect(Collectors.toList());
        }
        @Override
        protected List<String> getCheckVarsKey() {
            return List.of("customCandidatePosts");
        }
    }
    /**根据发起人获取用户*/
    public static class CustomCandidateStartUser extends CandidateUserHandle{
        protected List<String> getUserList(){
            return Arrays.asList(vars.get("startUserId")+"");
        }
        @Override
        protected List<String> getCheckVarsKey() {
            return List.of();
        }
    }

    /**根据发起人部门同事获取用户*/
    public static class CustomCandidateStartUserEqDept extends CandidateUserHandle{
        protected List<String> getUserList(){
            String startUserId = vars.get("startUserId")+"";
            SysUser sysUser = getSysUserMapper().selectUserById(Long.valueOf(startUserId));
            String posts = getTaskAttributes("customCandidatePosts");
            List<String> postNameList = Arrays.asList(posts.split(",")).stream().filter(r->StrUtil.isNotBlank(r)).collect(Collectors.toList());
            List<SysUser> userList = getSysDeptMapper().selectUserByDeptIds(Arrays.asList(sysUser.getDeptId()+""),postNameList);
            return userList.stream().map(r->r.getUserId()+"").collect(Collectors.toList());
        }
        @Override
        protected List<String> getCheckVarsKey() {
            return List.of();
        }
    }

    /**根据发起人同机构获取用户*/
    public static class CustomCandidateStartUserEqUnit extends CandidateUserHandle{
        protected List<String> getUserList(){
            String startUserId = vars.get("startUserId")+"";
            SysUser sysUser = getSysUserMapper().selectUserById(Long.valueOf(startUserId));
            SysDept userDept = getSysDeptMapper().selectDeptById(sysUser.getDeptId());
            List<SysDept> deptList = getSysDeptMapper().selectChildrenAndSelfById(userDept.getRootDeptId());
            List<String> deptIds = deptList.stream().map(r->r.getDeptId()+"").collect(Collectors.toList());
            String posts = getTaskAttributes("customCandidatePosts");
            List<String> postNameList = Arrays.asList(posts.split(",")).stream().filter(r->StrUtil.isNotBlank(r)).collect(Collectors.toList());
            List<SysUser> userList = getSysDeptMapper().selectUserByDeptIds(deptIds,postNameList);
            return userList.stream().map(r->r.getUserId()+"").collect(Collectors.toList());
        }
        @Override
        protected List<String> getCheckVarsKey() {
            return List.of();
        }
    }
    /**根据发起人上机构获取用户*/
    public static class CustomCandidateStartUserSuperUnit extends CandidateUserHandle{
        protected List<String> getUserList(){
            String startUserId = vars.get("startUserId")+"";
            SysUser sysUser = getSysUserMapper().selectUserById(Long.valueOf(startUserId));
            SysDept userDept = getSysDeptMapper().selectDeptById(sysUser.getDeptId());
            List<SysDept> deptList = getSysDeptMapper().selectChildrenAndSelfById(userDept.getParentRootDeptId());
            List<String> deptIds = deptList.stream().map(r->r.getDeptId()+"").collect(Collectors.toList());
            String posts = getTaskAttributes("customCandidatePosts");
            List<String> postNameList = Arrays.asList(posts.split(",")).stream().filter(r->StrUtil.isNotBlank(r)).collect(Collectors.toList());
            List<SysUser> userList = getSysDeptMapper().selectUserByDeptIds(deptIds,postNameList);
            return userList.stream().map(r->r.getUserId()+"").collect(Collectors.toList());
        }
        @Override
        protected List<String> getCheckVarsKey() {
            return List.of();
        }
    }
    /**根据前一审批人部门同事获取用户*/
    public static class CustomCandidatePrevUserDept extends CandidateUserHandle{
        protected List<String> getUserList(){
            SysUser sysUser = getSysUserMapper().selectUserById(Long.valueOf(lastAuditUserId));
            SysDept userDept = getSysDeptMapper().selectDeptById(sysUser.getDeptId());
            List<SysDept> deptList = getSysDeptMapper().selectChildrenAndSelfById(userDept.getDeptId());
            List<String> deptIds = deptList.stream().map(r->r.getDeptId()+"").collect(Collectors.toList());
            String posts = getTaskAttributes("customCandidatePosts");
            List<String> postNameList = Arrays.asList(posts.split(",")).stream().filter(r->StrUtil.isNotBlank(r)).collect(Collectors.toList());
            List<SysUser> userList = getSysDeptMapper().selectUserByDeptIds(deptIds,postNameList);
            return userList.stream().map(r->r.getUserId()+"").collect(Collectors.toList());
        }
        @Override
        protected List<String> getCheckVarsKey() {
            return List.of();
        }
    }

    /**根据前一审批人部门分管领导*/
    public static class CustomCandidatePrevUserDeptLeader extends CandidateUserHandle{
        protected List<String> getUserList(){
            SysUser sysUser = getSysUserMapper().selectUserById(Long.valueOf(lastAuditUserId));
            List<SysUser> userList = getSysUserMapper().findByManagerDeptIds(sysUser.getDeptId());
            return userList.stream().map(r->r.getUserId()+"").collect(Collectors.toList());
        }
        @Override
        protected List<String> getCheckVarsKey() {
            return List.of();
        }
    }

    /**
     * 上一审批人部门领导
     */
    public static class CustomCandidatePrevUserInDeptLeader extends CandidateUserHandle{
        protected List<String> getUserList(){
            SysUser sysUser = getSysUserMapper().selectUserById(Long.valueOf(lastAuditUserId));

            SysDept dept = getSysDeptMapper().selectById(sysUser.getDeptId());
            List<String> userIdList = new  ArrayList<>();
            if(dept.getLeaderUserId() != null){
                userIdList.add(dept.getLeaderUserId()+"");
            }
            return userIdList;
        }
        @Override
        protected List<String> getCheckVarsKey() {
            return List.of();
        }
    }


    /**根据前一审批人同机构获取用户*/
    public static class CustomCandidatePrevUserUnit extends CandidateUserHandle{
        protected List<String> getUserList(){
            SysUser sysUser = getSysUserMapper().selectUserById(Long.valueOf(lastAuditUserId));
            SysDept userDept = getSysDeptMapper().selectDeptById(sysUser.getDeptId());
            List<SysDept> deptList = getSysDeptMapper().selectChildrenAndSelfById(userDept.getRootDeptId());
            List<String> deptIds = deptList.stream().map(r->r.getDeptId()+"").collect(Collectors.toList());
            String posts = getTaskAttributes("customCandidatePosts");
            List<String> postNameList = Arrays.asList(posts.split(",")).stream().filter(r->StrUtil.isNotBlank(r)).collect(Collectors.toList());
            List<SysUser> userList = getSysDeptMapper().selectUserByDeptIds(deptIds,postNameList);
            return userList.stream().map(r->r.getUserId()+"").collect(Collectors.toList());
        }
        @Override
        protected List<String> getCheckVarsKey() {
            return List.of();
        }
    }
    /**根据前一审批人上级机构获取用户*/
    public static class CustomCandidatePrevUserSuperUnit extends CandidateUserHandle{
        protected List<String> getUserList(){
            SysUser sysUser = getSysUserMapper().selectUserById(Long.valueOf(lastAuditUserId));
            SysDept userDept = getSysDeptMapper().selectDeptById(sysUser.getDeptId());
            List<SysDept> deptList = getSysDeptMapper().findByRootDeptId(userDept.getParentRootDeptId());
            List<String> deptIds = deptList.stream().map(r->r.getDeptId()+"").collect(Collectors.toList());
            String posts = getTaskAttributes("customCandidatePosts");
            List<String> postNameList = Arrays.asList(posts.split(",")).stream().filter(r->StrUtil.isNotBlank(r)).collect(Collectors.toList());
            List<SysUser> userList = getSysDeptMapper().selectUserByDeptIds(deptIds,postNameList);
            return userList.stream().map(r->r.getUserId()+"").collect(Collectors.toList());
        }
        @Override
        protected List<String> getCheckVarsKey() {
            return List.of();
        }
    }
    /**根据变量动态获取用户*/
    public static class CustomCandidateDynamic extends CandidateUserHandle{
        protected List<String> getUserList(){
            String customCandidateUsersExp = userTask.getAttributes().get("customCandidateUsersExp").get(0).getValue();
            String []  userIdArray = ((String)vars.get(customCandidateUsersExp)).split(",");
            return Arrays.asList(userIdArray);
        }
        @Override
        protected List<String> getCheckVarsKey() {
            return List.of("customCandidateUsersExp");
        }
    }
    public CandidateUserHandle getCandidateUserHandle(UserTask userTask, Task task,Map processVariables){
        List<ExtensionAttribute> specifyUserMethodValues = userTask.getAttributes().get("specifyUserMethod");
        if(CollectionUtils.isEmpty(specifyUserMethodValues)){
            return null;
        }
        String specifyUserMethod = specifyUserMethodValues.get(0).getValue();
        CandidateUserHandle candidateUserHandle = null;
        if("人员".equals(specifyUserMethod)){
            candidateUserHandle = new CustomCandidateUsers();
        }else if("部门".equals(specifyUserMethod)){
            candidateUserHandle = new CustomCandidateDepts();
        }else if ("发起人自己".equals(specifyUserMethod)){
            candidateUserHandle = new CustomCandidateStartUser();
        }else if ("发起人部门同事".equals(specifyUserMethod)){
            candidateUserHandle = new CustomCandidateStartUserEqDept();
        }else if ("发起人同机构".equals(specifyUserMethod)){
            candidateUserHandle = new CustomCandidateStartUserEqUnit();
        }else if ("发起人上级机构".equals(specifyUserMethod)){
            candidateUserHandle = new CustomCandidateStartUserSuperUnit();
        }else if ("上一审批人部门同事".equals(specifyUserMethod)){
            candidateUserHandle = new CustomCandidatePrevUserDept();
        }else if ("上一审批人部门分管领导".equals(specifyUserMethod)){
            candidateUserHandle = new CustomCandidatePrevUserDeptLeader();
        }else if ("上一审批人部门领导".equals(specifyUserMethod)){
            candidateUserHandle = new CustomCandidatePrevUserInDeptLeader();
        }else if ("上一审批人同机构".equals(specifyUserMethod)){
            candidateUserHandle = new CustomCandidatePrevUserUnit();
        }else if ("上一审批人上级机构".equals(specifyUserMethod)){
            candidateUserHandle = new CustomCandidatePrevUserSuperUnit();
        }else if ("动态指定".equals(specifyUserMethod)){
            candidateUserHandle = new CustomCandidateDynamic();
        }
        if(candidateUserHandle!=null){
            candidateUserHandle.setUserTask(userTask);
            candidateUserHandle.setTask(task);

            if(task == null){
                candidateUserHandle.setVars(processVariables);
            }else{
                Map runtimeVars = getRuntimeService().getVariables(task.getProcessInstanceId());
                Map vars = task.getProcessVariables();
                if(vars.isEmpty()){
                    vars.putAll(runtimeVars);
                }
                vars.putAll(task.getTaskLocalVariables());
                vars.putAll(processVariables);
                candidateUserHandle.setVars(vars);
            }
            candidateUserHandle.setLastAuditUserId((String) candidateUserHandle.getVars().get("lastAuditUserId"));
        }
        return candidateUserHandle;
    }
}
